local skynet = require "skynet"
-- local snax = require "snax"
local socket = require "skynet.socket"
-- local ws_server = require "ws.ws_server"

local wsserver_port = skynet.getenv "wsserver_port"
wsserver_port = tonumber(wsserver_port)

local maxclient = skynet.getenv "maxclient"
maxclient = tonumber(maxclient)
local server

local connection = {}
local useragent = {}
local CMD = {}

local function close_fd(fd)
	local c = connection[fd]
	if c then
		c.agent = nil
		connection[fd] = nil
	end
end

local function connect(fd, addr)
	skynet.error("connect ",fd,addr)
	local agent = skynet.newservice("wsagent", fd, addr,skynet.self())
	local c = {
		fd = fd,
		ip = addr,
		agent = agent
	}
	connection[fd] = c
end


function CMD.open(fd,uid)
	local id = useragent[uid]
	if id then
		CMD.kick(uid)
	end
	useragent[uid] = connection[fd]
end

function CMD.close(fd,uid)
	close_fd(fd)
	useragent[uid] = nil
end

function CMD.kick(uid)
	local fd = useragent[uid]
	if fd then
		local c = connection[fd]
		if c then
			skynet.send(c.agent, "lua", "send_close")
			close_fd(fd)
			useragent[uid] = nil
		end
	end
end

function CMD.sendbroadcast( ... )
	for k,v in pairs(connection) do
		if v then
			skynet.send(v.agent, "lua", ...)
		end
	end
end

function CMD.start( conf )
	server = conf.server
	maxclient = conf.maxclient
end

skynet.start(function()	
	skynet.error("ws start " .. wsserver_port)
	skynet.dispatch("lua", function(session, source, cmd,...)
		local f = assert(CMD[cmd])
		if f then
			skynet.ret(skynet.pack(f(...)))
		end
	end)

	local id = socket.listen("0.0.0.0",wsserver_port)
	-- print(id)
	socket.start(id, function(id2, addr)
		connect(id2, addr)
	end)
end)
